package com.iqilu.ksd.view;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.RadioBean;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Coofee on 2016/11/9.
 */

public class RadioPlayerView extends RelativeLayout implements MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {

    private Context context;
    private RadioBean data;
    private Animation roateAni;
    private int mProgress = 0;
    private Boolean isPlay = false; //是否立即播放
    private MediaPlayer mediaPlayer;
    private Timer mTimer = new Timer();

    private SimpleDraweeView imgThumb;
    private ImageView btPlay;
    private TextView tvTime;
    private TextView tvDuration;
    private SeekBar skProgress;

    public RadioPlayerView(Context context) {
        super(context);
        this.context = context;
        bind();
    }

    public RadioPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        bind();
    }

    public RadioPlayerView(Context context, RadioBean data) {
        super(context);
        this.context = context;
        this.data = data;
        bind();
    }

    public void setData(RadioBean data) {
        setData(data, true);
    }

    public void setData(RadioBean data, Boolean isPlay) {
        this.data = data;
        this.isPlay = isPlay;
        imgThumb.setImageURI(Uri.parse(data.getThumb()));
        btPlay.setImageResource(R.drawable.bt_radio_play);
        initMediaPlayer();
        try {
            mediaPlayer.setDataSource(data.getFileurl());
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void bind() {
        RelativeLayout view = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.activity_radiodetail_player, null);
        imgThumb = (SimpleDraweeView) view.findViewById(R.id.img_thumb);
        btPlay = (ImageView) view.findViewById(R.id.bt_play);
        tvTime = (TextView) view.findViewById(R.id.tv_time);
        tvDuration = (TextView) view.findViewById(R.id.tv_duration);
        skProgress = (SeekBar) view.findViewById(R.id.sk_progress);
        skProgress.setOnSeekBarChangeListener(this);
        mTimer.schedule(mTimerTask, 0, 1000);

        roateAni = AnimationUtils.loadAnimation(context, R.anim.rotate_radio);
        LinearInterpolator lin = new LinearInterpolator();
        roateAni.setInterpolator(lin);

        btPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && data != null) {
                    if (mediaPlayer.isPlaying()) {
                        pause();
                    } else {
                        start();
                    }
                }
            }
        });

        this.addView(view);
    }

    private void initMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } else {
            mediaPlayer.reset();
        }
    }

    TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            if (mediaPlayer.isPlaying() && skProgress.isPressed() == false) {
                handleProgress.sendEmptyMessage(0);
            }
        }
    };

    Handler handleProgress = new Handler() {
        public void handleMessage(Message msg) {

            int position = mediaPlayer.getCurrentPosition();
            int duration = mediaPlayer.getDuration();

            if (duration > 0) {
                SimpleDateFormat format = new SimpleDateFormat("mm:ss");
                Date curDate = new Date(position);
                Date totalDate = new Date(duration);
                tvTime.setText(format.format(curDate));
                tvDuration.setText(format.format(duration));
                long pos = skProgress.getMax() * position / duration;
                skProgress.setProgress((int) pos);
            }
        }

        ;
    };

    public void start() {
        mediaPlayer.start();
        btPlay.setImageResource(R.drawable.bt_radio_pause);
        imgThumb.startAnimation(roateAni);

    }

    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            btPlay.setImageResource(R.drawable.bt_radio_play);
            imgThumb.clearAnimation();
        }
    }

    public void pause() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            btPlay.setImageResource(R.drawable.bt_radio_play);
            imgThumb.clearAnimation();
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        imgThumb.clearAnimation();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        if (isPlay) {
            start();
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        mProgress = progress * mediaPlayer.getDuration() / seekBar.getMax();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(mProgress);
    }
}
